#include "head.h"

// 子线程的入口
void * pthread_fun(void *p){
//printf("in -----------\n");
    pool_t *pool = (pool_t *)p;

    pthread_mutex_lock(&pool->pthread_lock);
    // 去队列中拿任务
    if (pool->queue.size <= 0){ 
        pthread_cond_wait(&pool->cond, &pool->pthread_lock);
    }   
    int net_fd = pool->queue.head->net_fd;
    // 删除
    de_queue(&pool->queue);
    pthread_mutex_unlock(&pool->pthread_lock);

    //读配置文件，获取数据库信息
    char sql_owner[100] = { 0 };//这个是存所有者“root”的
    char sql_password[100] = { 0 };                                                   
    char sql_name[100] = { 0 };//这个是库名称， “netDisk”
    getparameter("sql_owner", sql_owner);
    getparameter("sql_password", sql_password);
    getparameter("sql_name", sql_name);
 //   printf("初始化-----------\n");

    //建立数据连接
    pthread_mutex_lock(&pool->pthread_lock);
    MYSQL *conn;
    conn = mysql_init(NULL);
    if (!mysql_real_connect(conn, NULL, sql_owner, sql_password, sql_name, 0, NULL, 0)){
        printf( "%s\n", mysql_error(conn));
        exit(1);
    }    
    pthread_mutex_unlock(&pool->pthread_lock);
    mysql_set_character_set(conn, "utf8mb4");

//    printf("-----------\n");
    
    //接收命令
    while(1){
        //接收token
        char token[255] = {0};
        int res_recv = recv(net_fd, token, sizeof(token), 0);
        ERROR_CHECK(res_recv, -1, "recv");

        //解密：获取用户名
        char uname[100] = { 0 };
        decode(uname, token);
        printf("worker 47 uname:%s\n", uname);

        // 接收命令
        char buf_cmd[100] = {0};
        recv(net_fd, buf_cmd, sizeof(buf_cmd), 0);
        ERROR_CHECK(res_recv, -1, "recv");

        if (strcmp(buf_cmd, "") != 0){

            printf("client cmd: %s\n", buf_cmd);
            // 将命令头转换为枚举类型
            char *cmd_head;
            char *cmd_body;
            COMMAND cmd;
            cmd_head = strtok(buf_cmd, " ");
            printf("cmd head : %s\n", cmd_head);
            if (strcmp(cmd_head, "upload") == 0) {
                cmd = upload;
                cmd_body = strtok(NULL, "\n");
                printf("cmd body : %s\n", cmd_body);
            } else if (strcmp(cmd_head, "download") == 0) {
                cmd = download;
                cmd_body = strtok(NULL, "\n");
                printf("cmd body : %s\n", cmd_body);
            }

            // 根据命令调用相应函数
            switch (cmd){
            case upload: recv_bigfile(net_fd, cmd_body, uname, conn); break;
            case download: send_bigfile(net_fd, cmd_body, uname, conn); break;
            default:break;
            }
        }else{
           continue; 
        }
    }
}
